<!DOCTYPE html>
<html>

<head>
	<meta charset="utf-8">
	<title></title>
	<style type="text/css">
		* {
			margin: 0;
			padding: 0;
		}

		.min-box {
			position: relative;
			top: 0px;
			left: 0px;
			margin-top: 100px;
			margin-left: 100px;
			width: 450px;
			height: 450px;
			border: 1px solid orange;
			cursor: move;
		}

		.min-box,
		.max-box {
			float: left;
		}

		.mask {
			position: absolute;
			top: 0;
			left: 0;
			width: 200px;
			height: 200px;
			background-color: rgba(0, 0, 0, .3);
			display: none;
		}

		.max-box {
			position: relative;
			border: 1px solid blue;
			width: 600px;
			height: 600px;
			overflow: hidden;
			display: none;
		}

		.max-img {
			position: absolute;
			top: 0;
			left: 0;
		}
	</style>
</head>

<body>
	<div class="min-box">
		<img src="./img/微信图片_20240415151601.jpg" class="min-img" alt="">
		<div class="mask"></div>
	</div>
	<div class="max-box">
		<img src="./img/微信图片_20240415151539.jpg" class="max-img" alt="">
	</div>
	<script type="text/javascript">
		var minBox = document.getElementsByClassName('min-box')[0];
		var minImg = document.getElementsByClassName('min-img')[0];
		var mask = document.getElementsByClassName('mask')[0];
		var maxBox = document.getElementsByClassName('max-box')[0];
		var maxImg = document.getElementsByClassName('max-img')[0];

		//1 鼠标悬停蒙版和大盒子显示
		minBox.onmouseover = function (e) {
			mask.style.display = 'block';
			maxBox.style.display = 'block';
			//2 蒙版跟随鼠标移动
			document.onmousemove = function (e) {
				//2.1 获取鼠标的在盒子中坐标
				// x轴 = 当前光标的距离浏览器的位置(包含外边距)-自身偏移量
				var x = e.pageX - minBox.offsetLeft;
				var y = e.pageY - minBox.offsetTop;
				//2.2 蒙版跟随鼠标进行移动, 并且在正中央
				// 光标在浏览器的位置-自身一半
				var maskY = y - mask.offsetHeight / 2;
				var maskX = x - mask.offsetWidth / 2;
				//获取偏移量
				// 获取最大偏移量
				var maxTop = minBox.offsetHeight - mask.offsetHeight;
				var maxLeft = minBox.offsetWidth - mask.offsetWidth;
				if (maskX < 0) {
					maskX = 0;
				}
				if (maskY < 0) {
					maskY = 0;
				}
				if (maskX > maxLeft) {
					maskX = maxLeft;
				}
				if (maskY > maxTop) {
					maskY = maxTop;
				}
				mask.style.top = maskY + 'px';
				mask.style.left = maskX + 'px';

				//3 大图片跟随蒙版移动	
				maxImg.style.top = maskY * (maxBox.offsetHeight - maxImg.offsetHeight) / maxTop + 'px';
				maxImg.style.left = maskX * (maxBox.offsetWidth - maxImg.offsetWidth) / maxLeft + 'px';
			}
		}
		//4 鼠标离开蒙版和大盒子隐藏
		minBox.onmouseout = function (e) {
			mask.style.display = 'none';
			maxBox.style.display = 'none';
		}
	</script>
</body>

</html>